document.addEventListener("DOMContentLoaded", function() {
  // 全局变量和常量
  const protocol = window.location.protocol === "https:" ? "wss" : "ws";
  const wsUrl = protocol + "://" + window.location.host + "/ws/chat";
  let socket = null;
  const chatBox = document.getElementById("chat-box");
  const messageInput = document.getElementById("message-input");
  const sendBtn = document.getElementById("send-btn");

  // 用于累积机器人返回的文本
  let currentBotMessageElem = null;
  let currentBotRawText = "";

  // ---------- 自定义 Markdown 解析器 ----------
  function customMarkdownParser(text) {
    // 1. 先处理多级标题：匹配行首以 1-6 个 # 开头的标题，直到换行、<br> 或文本末尾
    text = text.replace(/^(#{1,6})\s+(.*?)(?=\n|<br>|$)/gm, function(match, hashes, title) {
      const level = hashes.length;
      return `<h${level}>${title.trim()}</h${level}>`;
    });
    
    // 2. 处理加粗：**text** 或 __text__
    text = text.replace(/(\*\*|__)(.*?)\1/g, '<strong>$2</strong>');
    // 3. 处理斜体：*text* 或 _text_
    text = text.replace(/(\*|_)(.*?)\1/g, '<em>$2</em>');
    // 4. 处理代码块：```code```
    text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
    // 5. 处理行内代码：`code`
    text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
    // 6. 处理表格：简单实现（仅支持单行表格）
    text = text.replace(/\|(.+?)\|/g, function(match, p1) {
      const cells = p1.split("|").map(cell => `<td>${cell.trim()}</td>`).join("");
      return `<table><tr>${cells}</tr></table>`;
    });
    // 7. 处理链接：[text](url)
    text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
    // 8. 处理引用：行首以 ">" 开头的文本
    text = text.replace(/^>\s*(.*)$/gm, '<blockquote>$1</blockquote>');
    // 9. 处理有序列表：匹配连续以 "数字. " 或 "数字) " 开头的行
    text = parseOrderedLists(text);
    // 10. 处理无序列表：匹配连续以 "-" 或 "*" 开头的行
    text = parseUnorderedLists(text);
    // 11. 分割线：保持原文（不转换）
    // 12. 最后，将剩余的换行符全部转换为 <br> 保留原始换行
    text = text.replace(/\n/g, '<br>');
    return text;
  }

  // 解析有序列表：匹配连续以 "数字. " 或 "数字) " 开头的行
  function parseOrderedLists(text) {
    return text.replace(/((?:^|\n)(?:\d+[\.)]\s+.*(?:\n|$))+)/g, function(match) {
      const lines = match.trim().split(/\n/);
      const items = lines.map(line => line.replace(/^\d+[\.)]\s+/, '').trim());
      return '\n<ol><li>' + items.join('</li><li>') + '</li></ol>\n';
    });
  }

  // 解析无序列表：匹配连续以 "-" 或 "*" 开头的行
  function parseUnorderedLists(text) {
    return text.replace(/((?:^|\n)(?:[-*]\s+.*(?:\n|$))+)/g, function(match) {
      const lines = match.trim().split(/\n/);
      const items = lines.map(line => line.replace(/^[-*]\s+/, '').trim());
      return '\n<ul><li>' + items.join('</li><li>') + '</li></ul>\n';
    });
  }

  // ---------- 将机器人返回的原始文本转换为 HTML ----------
  function transformBotText(rawText) {
    let html = "";
    let remaining = rawText;
    const regex = /^(.*?)<think>([\s\S]*?)<\/think>([\s\S]*)$/;
    // 处理带有 <think> 标签的文本
    while (true) {
      const match = remaining.match(regex);
      if (match) {
        const before = match[1].trim();
        const thinkContent = match[2].trim();
        const after = match[3];
        if (before) {
          html += `<p>${before}</p>`;
        }
        html += `<div class="think-block"><strong>思考:</strong> ${thinkContent}</div>`;
        remaining = after;
      } else {
        break;
      }
    }
    if (remaining.trim()) {
      html += `<p>${remaining.trim()}</p>`;
    }
    return customMarkdownParser(html);
  }

  // ---------- WebSocket 连接及消息处理 ----------
  function connectWebSocket(callback) {
    socket = new WebSocket(wsUrl);
    socket.onopen = function() {
      console.log("WebSocket 已连接");
      const sysMsg = document.createElement("p");
      sysMsg.innerHTML = "<em>系统：WebSocket 连接已建立</em>";
      chatBox.appendChild(sysMsg);
      chatBox.scrollTop = chatBox.scrollHeight;
      socket.onmessage = handleMessage;
      socket.onerror = handleError;
      socket.onclose = handleClose;
      if (callback) callback();
    };
    socket.onmessage = handleMessage;
    socket.onerror = handleError;
    socket.onclose = handleClose;
  }
  connectWebSocket();

  function handleMessage(event) {
    console.log("收到消息:", event.data);
    // 判断是否收到结束标记（例如 "<｜end▁of▁sentence｜>" 或 "[END]"）
    if (event.data.indexOf("<｜end▁of▁sentence｜>") !== -1 || event.data === "[END]") {
      let incremental = "";
      if (event.data.indexOf("<｜end▁of▁sentence｜>") !== -1) {
        incremental = event.data.replace("<｜end▁of▁sentence｜>", "");
      }
      currentBotRawText += incremental;
      if (currentBotMessageElem) {
        currentBotMessageElem.innerHTML = "<strong class='bot-name'>机器人:</strong>" + transformBotText(currentBotRawText);
      }
      chatBox.scrollTop = chatBox.scrollHeight;
      if (currentBotMessageElem && currentBotMessageElem.innerText.trim() === "机器人:") {
        chatBox.removeChild(currentBotMessageElem);
      }
      messageInput.disabled = false;
      sendBtn.disabled = false;
      currentBotMessageElem = null;
      currentBotRawText = "";
      return;
    } else {
      currentBotRawText += event.data;
      if (!currentBotMessageElem) {
        currentBotMessageElem = document.createElement("div");
        currentBotMessageElem.innerHTML = "<strong class='bot-name'>机器人:</strong>" + transformBotText(currentBotRawText);
        chatBox.appendChild(currentBotMessageElem);
      } else {
        currentBotMessageElem.innerHTML = "<strong class='bot-name'>机器人:</strong>" + transformBotText(currentBotRawText);
      }
      chatBox.scrollTop = chatBox.scrollHeight;
    }
  }

  function handleError(error) {
    console.error("WebSocket 错误：", error);
  }

  function handleClose() {
    console.log("WebSocket 连接关闭");
    const sysMsg = document.createElement("p");
    sysMsg.innerHTML = "<em>系统：WebSocket 连接已断开</em>";
    chatBox.appendChild(sysMsg);
    chatBox.scrollTop = chatBox.scrollHeight;
  }

  // ---------- 消息发送 ----------
  function sendMessage() {
    const message = messageInput.value.trim();
    if (message === "") return;
    if (!socket || socket.readyState !== WebSocket.OPEN) {
      console.log("WebSocket 未连接，正在重连...");
      connectWebSocket(function() {
        sendMessageNow(message);
      });
    } else {
      sendMessageNow(message);
    }
  }

  function sendMessageNow(message) {
    const userMsgElem = document.createElement("p");
    userMsgElem.innerHTML = "<strong class='user-name'>我:</strong> " + message;
    chatBox.appendChild(userMsgElem);
    chatBox.scrollTop = chatBox.scrollHeight;
    socket.send(message);
    messageInput.value = "";
    messageInput.disabled = true;
    sendBtn.disabled = true;
  }

  // 绑定按钮点击和回车键事件
  sendBtn.addEventListener("click", sendMessage);
  messageInput.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
      sendMessage();
    }
  });
});
